// 晶体绑定维护
import React from 'react';
import { Card, Row, Col, Form, Table, Select, Input, Button, message, Switch, } from 'antd';
import CommonPagination from 'components/pagination/index';
import PublicModalTable from 'pages/common/PublicModalTable';
import { $http } from 'containers/config/https';
import './style/index.less';
import store from 'store';

const { Option } = Select;
const formItemInput = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 10 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
};
const CrystalBindingMaintenance = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                medDesc: "",
                brandListData: [],
                rowKey: "",
                page: 1,
                degreesList: [],
                pageSize: 10,
                top: '',
                left: '',
                medDesc: '',
                modalRowId: '',
                stockDesc: '',
                stockID: '',
                total: '',
                ruleList: [],
                languageData:[],
                modalData: [{ "key": "1", "stockDesc": "人工晶状体", "stockCode": "23.5D", "stockSpec": "1322152321" },
                { "key": "2", "stockDesc": "人工晶状体", "stockCode": "23.5D", "stockSpec": "1322152321" },
                { "key": "3", "stockDesc": "人工晶状体", "stockCode": "23.5D", "stockSpec": "1322152321" },
                { "key": "4", "stockDesc": "人工晶状体", "stockCode": "23.5D", "stockSpec": "1322152321" }]
            }

            this.columns = [
                {
                    key: 1,
                    title: '晶体名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 2,
                    title: '晶体代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 3,
                    title: '晶体规格',
                    dataIndex: 'stockSpec',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 4,
                    title: '晶体度数',
                    dataIndex: 'degreesDesc',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 5,
                    title: '晶体序列码',
                    dataIndex: 'serialNo',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 6,
                    title: '晶体条码',
                    dataIndex: 'barCode',
                    align: "center",
                    width: '20%'
                }
                ,
                {
                    key: 7,
                    title: '规则',
                    dataIndex: 'ruleDesc',
                    align: "center",
                    width: '20%'
                }
            ];
            this.modalColumns = [
                {
                    key: 1,
                    title: '晶体代码',
                    dataIndex: 'stockCode',
                    align: "center",
                },
                {
                    key: 2,
                    title: '晶体名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                },
                {
                    key: 3,
                    title: '晶体规格',
                    dataIndex: 'stockSpec',
                    align: "center",
                },
            ];
            this.myRef1 = React.createRef();
        }

        componentDidMount() {
            // 初始化数据
            this.getSelect()
            this.getTableColumns()
        }
        // 晶体绑定table
        getTableColumns = () => {
            let data = {
                params: [{
                    "reactCode": ["CrystalBinding"],
                    "compontName": "CrystalBinding",
                    "type": "C"

                }]
            }
            $http.post('urlS', this, {
                code: "01040073",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            languageData: res.result.C || [],  // 国际化语言包
                        })
                    }
                }
            });
        }


        // 键盘操作名称模态框数据
        handlePublicModalTableOnKeydown = (e) => {
            var e = window.event || e;
            let scroll_height = 26;
            let id = '';
            let oneArr = this.state.modalData && this.state.modalData.length > 0 ? this.state.modalData : [];
            switch (e.keyCode) {
                case 13:
                    if (this.state.modalRowId) {
                        let obj = {}
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                obj = i > 0 ? oneArr[i] : oneArr[0];
                                break;
                            }
                        }
                        this.confirmSelection(obj);
                    } else {
                        message.info("报错")
                    }
                    break;
                case 38: //上
                    if (this.state.modalRowId) {
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong");
                            gundong.scrollTop = gundong.scrollTop - scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
                case 40: //下
                    if (this.state.modalRowId) {
                        for (let i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong");
                            gundong.scrollTop = gundong.scrollTop + scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
            }
        };
        // 操作弹框
        onClickRowPublic = (record) => {
            return {
                onDoubleClick: () => {
                    this.confirmSelection(record);
                }
            }
        }
        // 双击选中行数据的回调
        confirmSelection = (record) => {
            console.log("record", record)
            this.props.form.setFieldsValue({ stockDesc: record.stockDesc })
            this.setState({ stockDesc: record.stockDesc, stockID: record.ID }, () => {
                this.child.handleCancel();
            })
        }
        setRowClassNamePublic = (record) => {
            return record.key === this.state.modalRowId ? 'clickRowStyle' : '';
        }

        onRef = (ref) => {
            this.child = ref;
        }
        // 修改名称列表条数以及列数
        compilePage = (page, pageSize) => {
            this.setState({ page, pageSize }, () => {
                //this.getModalListData()
            })
        }
        // 名称回车事件
        nameOnPressEnter = (e) => {
            if (!e.target.value) {
                message.info("请输入名称回车搜索")
                return;
            }
            let top = document.getElementById('name-input').getBoundingClientRect().top + 40 + 'px';
            let left = document.getElementById('name-input').getBoundingClientRect().left + 'px';
            this.setState({
                top: top,
                left: left,
                medDesc: e.target.value
            }, () => {
                this.getModalListData("show");
            });
        }
        // 获取描述列表数据
        getModalListData = (isShow) => {
            let { medDesc } = this.state;
            let data = {
                params: [
                    {
                        search: medDesc,
                    }
                ]
            }
            $http.post('urlS', this, {
                code: "02020365",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result ? res.result : [];
                        for (var i = 0; i < arr.length; i++) {
                            arr[i].key = i + 1
                        }
                        this.setState({ modalData: arr, total: res.result.totalCount, modalRowId: arr && arr.length > 0 ? arr[0].key : '' }, () => {
                            isShow === 'show' ? this.child.showModal() : '';
                        })
                    } else {
                        this.setState({ modalData: [], total: 0 });
                        isShow === 'show' ? this.child.showModal() : '';
                    }
                },
                error: function () {
                    this.setState({ modalData: [], total: 0 });
                    isShow === 'show' ? this.child.showModal() : '';
                }
            })
        }
        // 名称失焦操作
        handleOnBlur = (e) => {
            if (this.state.stockID) {
                let arr = this.state.modalData ? JSON.parse(JSON.stringify(this.state.modalData)) : '';
                let status = false;
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].stockDesc === e.target.value) {
                        status = true;
                        break;
                    }
                }
                if (!status) {
                    this.setState({ stockID: '', stockDesc: undefined })
                }
            } else {
                this.setState({ stockID: '', stockDesc: undefined })
            }
        }
        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态
            this.setState = (state, callback) => { return; }
        }


        // 查询
        handleQuery = () => {
            this.setState({ page: 1, pageSize: 10 }, () => {
                //查询
                this.getTableData();
            })
        }
        //获取晶体绑定数据
        getTableData = () => {
            let search = this.props.form.getFieldValue('search')
            let { pageSize, page } = this.state
            var data = {
                params: [{
                    search: search
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }

            $http.post('urlS', this, {
                code: "02020361",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            brandListData: res.result.rows,
                            total: res.result.total
                        });
                    } else {
                        this.setState({
                            brandListData: []
                        });
                    }
                }
            });
        }
        //获取度数下拉框
        getSelect = () => {
            var data = {
                params: [{
                }]
            }

            $http.post('urlS', this, {
                code: "02020362",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setState({
                            degreesList: res.result.degreesData,
                            ruleList: res.result.ruleData
                        });
                    } else {
                        this.setState({
                            degreesList: [],
                            ruleList: []
                        });
                    }
                }
            });
        }
        //修改/保存晶体绑定列表
        saveData = () => {
            let degreesID = this.props.form.getFieldValue('degreesID');
            let serialNo = this.props.form.getFieldValue('serialNo');
            let barCode = this.props.form.getFieldValue('barCode');
            let ruleID = this.props.form.getFieldValue('ruleID');
            if (this.state.stockID === "") {
                message.error("晶体不能为空")
                return
            }
            let { brandObj, stockID } = this.state
            console.log("stockID", stockID, this, this.state.stockID)
            var data = {
                params: [{
                    ID: brandObj && brandObj.ID ? brandObj.ID : '',
                    stockID: stockID,
                    degreesID: degreesID ? degreesID : '',
                    serialNo: serialNo ? serialNo : '',
                    barCode: barCode ? barCode : '',
                    ruleID: ruleID ? ruleID : ''
                }]
            }

            $http.post('urlS', this, {
                code: "02020363",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        message.success(res.errorMessage)
                        this.setState({ rowKey: '', brandObj: {}, stockID: '' }, () => {
                            this.props.form.setFieldsValue({ stockDesc: '', degreesID: '', serialNo: '', barCode: '', ruleID: '' })
                        });
                        this.getTableData()
                    } else {
                        //message.error(res.errorMessage)
                    }
                }
            });
        }
        //删除
        deleteData = () => {
            let { rowKey } = this.state
            console.log("rowKey", rowKey)
            if (rowKey === "") {
                message.error("请选择一条记录再删除。")
                return
            }

            var data = {
                params: [{
                    ID: rowKey ? rowKey : '',
                }]
            }

            $http.post('urlS', this, {
                code: "02020364",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        message.success(res.errorMessage)
                        this.setState({ rowKey: '', brandObj: {}, stockID: '' }, () => {
                            this.props.form.setFieldsValue({ stockDesc: '', degreesID: '', serialNo: '', barCode: '', ruleID: '' })
                        });
                        this.getTableData()
                    } else {
                        //message.error(res.errorMessage)
                    }
                }
            });
        }
        //根据序列号获取条码规则
        getRuleBySerNo = () => {
            let serialNo = this.props.form.getFieldValue('serialNo');
            let { stockID}=this.state
            if (serialNo === "") {
                message.error("请输入序列号。")
                return
            }
            if (stockID === "") {
                message.error("请输入一条晶体。")
                return
            }

            var data = {
                params: [{
                    stockID:stockID || '',
                    serialNo: serialNo ? serialNo : ''
                }]
            }

            $http.post('urlS', this, {
                code: "02060202",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.props.form.setFieldsValue({ barCode: res.result.barCode })
                    } else {
                        //message.error(res.errorMessage)
                    }
                }
            });
        }
        // 科室表格行的类名
        setLocClassName = (record) => {
            return record.id === this.state.rowLocKey ? 'clickRowStyle' : '';
        };

        // 角色表格行的类名
        setRowClassName = (record) => {
            return record.ID === this.state.rowKey ? 'clickRowStyle' : '';
        };
        // 设置角色行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({ rowKey: record.ID, brandObj: record, stockID: record.stockID }, () => {
                            this.props.form.setFieldsValue({ stockDesc: record.stockDesc ? record.stockDesc : '', degreesID: record.degreesID ? record.degreesID + '' : '', serialNo: record.serialNo ? record.serialNo : '', barCode: record.barCode ? record.barCode : '', ruleID: record.ruleID ? record.ruleID + '' : '' })
                        });

                    } else {
                        if (this.state.rowKey !== record.ID) {
                            this.setState({ rowKey: record.ID, brandObj: record, stockID: record.stockID }, () => {
                                this.props.form.setFieldsValue({ stockDesc: record.stockDesc ? record.stockDesc : '', degreesID: record.degreesID ? record.degreesID + '' : '', serialNo: record.serialNo ? record.serialNo : '', barCode: record.barCode ? record.barCode : '', ruleID: record.ruleID ? record.ruleID + '' : '' })
                            });
                        } else {
                            this.setState({ rowKey: '', brandObj: {}, stockID: '' }, () => {
                                this.props.form.setFieldsValue({ stockDesc: '', degreesID: '', serialNo: '', barCode: '', ruleID: '' })
                            });
                        }
                    }
                }
            }
        };
        // 页码改变的回调，参数是改变后的页码及每页条数 出库单
        onChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                this.getTableData();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({ page: current, pageSize: size }, () => {
                // 重新调用查询方法
                this.onChange(current, size);
            })
        };
        render() {
            const { getFieldDecorator } = this.props.form;
            let { brandObj, left, top, modalData, stockDesc,languageData } = this.state;
            let param = {
                width: '700px',
                height: 300,
                top: top,
                left: left,
                columns: this.modalColumns,
                data: modalData,
                isOnRow: true,
                TableClassName: 'tab-placeholder',
                rowClassName: true,
            }
            return (
                <div className="CrystalBindingMaintenance">
                    <Col span={12}>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{'查询条件'}</div>}
                        >
                            <Row>
                                <Col span={10}>
                                    <Form>
                                        <Row>
                                            <Col span={24} >
                                                <Form.Item label={'晶体名称：'} {...formItemInput}>
                                                    {getFieldDecorator('search', {
                                                        initialValue: undefined,
                                                    })(
                                                        <Input placeholder={'回车可搜索'} onPressEnter={this.handleQuery} style={{ width: '250px' }} />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </Form>
                                </Col>
                                <Col span={14} style={{ marginTop: '4px' }}>
                                    <Row >
                                        <Button style={{ marginLeft: '20px' }} onClick={this.handleQuery}>{'查询'}</Button>
                                    </Row>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{'晶体列表'}</div>}
                        >
                            <div>
                                <Table
                                    columns={languageData?languageData:this.columns}
                                    dataSource={this.state.brandListData}
                                    pagination={false}
                                    bordered
                                    scroll={{ y: store.getState().tableHeight.y - 13 }}
                                    style={{ height: (store.getState().tableHeight.y + 27) }}
                                    rowKey={record => record.key}
                                    className="tableDetailHeight"
                                    onRow={this.onClickRow}
                                    rowClassName={this.setRowClassName}
                                />
                                <CommonPagination size='small' current={this.state.page} total={this.state.total} search='search'
                                    onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.brandListData}
                                    onChange={this.onChange.bind(this)} />
                            </div>
                        </Card>
                    </Col>
                    <Col span={12}>
                        <Row >
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{'绑定条码'}</div>}
                            >
                                <div style={{ height: (store.getState().tableHeight.y + 178) }}  >
                                    <Row>
                                        <div id="name-input">
                                            <Form.Item label={'晶体名称：'} {...formItemInput}>
                                                {getFieldDecorator('stockDesc', {
                                                    initialValue: brandObj && brandObj.stockDesc ? brandObj.stockDesc : (stockDesc ? stockDesc : undefined),
                                                    rules: [{ required: '请选择入晶体名称' }]
                                                })(

                                                    <Input
                                                        onPressEnter={this.nameOnPressEnter}
                                                        placeholder=""
                                                        onBlur={this.handleOnBlur}
                                                        autoComplete="off"
                                                        allowClear
                                                        ref={this.myRef1}
                                                    />

                                                )}
                                            </Form.Item>
                                        </div>
                                        <div
                                            tabIndex={1}
                                            onKeyDown={this.handlePublicModalTableOnKeydown}
                                            style={{ outline: 'none' }}
                                        >
                                            <PublicModalTable
                                                onClickRowPublic={this.onClickRowPublic}
                                                setRowClassNamePublic={this.setRowClassNamePublic}
                                                param={param}
                                                onRef={this.onRef}
                                                compilePage={this.compilePage}
                                                id="gundong"
                                            />
                                        </div>
                                    </Row>
                                    <Row >
                                        <Form.Item label={'度数'} {...formItemInput}>
                                            {getFieldDecorator('degreesID', {
                                                initialValue: brandObj && brandObj.degreesDesc ? brandObj.degreesDesc : undefined,
                                                //rules: [{ required: '请选择晶体度数' }]
                                            })(
                                                <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100%' }}>
                                                    {this.state.degreesList && this.state.degreesList.length > 0 && this.state.degreesList.map(item => {
                                                        return <Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                                    })}
                                                </Select>
                                            )}
                                        </Form.Item>
                                    </Row>
                                    {/* <Row >
                                        <Form.Item label={'规则'} {...formItemInput}>
                                            {getFieldDecorator('ruleID', {
                                                initialValue: brandObj && brandObj.ruleID ? brandObj.ruleID : undefined,
                                                //rules: [{ required: '请选择晶体度数' }]
                                            })(
                                                <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100%' }}>
                                                    {this.state.ruleList && this.state.ruleList.length > 0 && this.state.ruleList.map(item => {
                                                        return <Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                                    })}
                                                </Select>
                                            )}
                                        </Form.Item>
                                    </Row> */}
                                    <Row>
                                        <Form.Item label={'晶体序列码：'} {...formItemInput}>
                                            {getFieldDecorator('serialNo', {
                                                initialValue: brandObj && brandObj.serialNo ? brandObj.serialNo : undefined,
                                            })(
                                                <Input onPressEnter={this.getRuleBySerNo} />
                                            )}
                                        </Form.Item>
                                    </Row>
                                    <Row>
                                        <Form.Item label={'晶体条码：'} {...formItemInput}>
                                            {getFieldDecorator('barCode', {
                                                initialValue: brandObj && brandObj.barCode ? brandObj.barCode : undefined,
                                            })(
                                                <Input />
                                            )}
                                        </Form.Item>
                                    </Row>
                                    <Row >
                                        <div className="btn-center" >
                                            <Button style={{ margin: '0 20px' }} onClick={this.saveData}>{'保存'}</Button>
                                            <Button onClick={this.deleteData}>{'删除'}</Button>
                                        </div>
                                    </Row>
                                </div>
                            </Card>
                        </Row>
                    </Col>
                </div>
            )
        }
    }
);
export default CrystalBindingMaintenance;